package top.natsu.reminder.cron;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import javafx.application.Platform;
import top.natsu.reminder.gui.RestLockWindows;
import top.natsu.reminder.gui.controller.IndexController;
import top.natsu.reminder.gui.controller.ReportController;
import top.natsu.reminder.handler.TimeRecord;
import top.natsu.reminder.util.ApplicationHolderUtil;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * /**
 *
 * @Description 定时器轮询检查当前工作时间
 * @Author shikanatsu
 * @Date 2022/3/28 0028 18:53
 **/
public class ClockActuator {

    private volatile static boolean isRun = false;

    private final static TimeRecord timeRecord = TimeRecord.getInstance();

    private static Integer preId = 0;

    public static CountDownLatch latch = new CountDownLatch(1);

    private static boolean isSequential;

    private static AtomicInteger sequentialCount = new AtomicInteger(0);

    /**
     * 默认休息时间5分钟后会自动的归零
     **/
    private static int maxRest = 5;

    /**
     * 疲劳值处理：
     * 每分钟轮询, 当前ID = 上一次的ID 则表示未操作，扣除对应的疲劳值, 当 > 上一次的ID则有操作，增加一点疲劳值(总疲劳为工作时间)
     **/
    public static void startTimer() {
        isRun = true;
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    //do Something
                    if (canRun()) {
                        doExecution();
                        ApplicationHolderUtil.getWindow(IndexController.class).setFatigueText(timeRecord.getFatigue().get());
                    }
                } catch (Exception e) {
                    ThreadUtil.sleep(1, TimeUnit.MINUTES);
                    e.printStackTrace();
                }
            }
        }, 0, 60000);
    }


    private static void doExecution() {
        int fatigue = timeRecord.getFatigue().get();
        if (timeRecord.getOperationId().get() <= preId) {
            System.out.println("未进行任何操作:疲劳值减少");
            if (timeRecord.getFatigue().get() != 0) {
                int vl = timeRecord.getFatigue().decrementAndGet();
                ApplicationHolderUtil.getWindow(ReportController.class).putXyData(timeRecord.getLastTime(), timeRecord.getFatigue().get(), true);
                System.out.println("当前疲劳值" + vl);
                //连续地休息才算休息
                if (sequentialCount.incrementAndGet() >= maxRest) {
                    //直接重置非常nice
                    timeRecord.reSetFatigue();
                    sequentialCount.set(0);
                }
            }
        } else {
            int i = timeRecord.getFatigue().incrementAndGet();
            System.out.println("操作中:疲劳值增加" + i);
            ApplicationHolderUtil.getWindow(ReportController.class).putXyData(timeRecord.getLastTime(), timeRecord.getFatigue().get(), false);
            if (sequentialCount.get() != 0) {
                sequentialCount.decrementAndGet();
            }
        }
        //change index report
//        ApplicationHolderUtil.getWindow(IndexController.class)
        ApplicationHolderUtil.getWindow(IndexController.class).
                setReportTime(timeRecord.getNowWorkTime(), timeRecord.getFatigue().get());
//        timeRecord.setNowWorkTime(timeRecord.getNowWorkTime() + 1);
        preId = timeRecord.getOperationId().get();
        Date time = new Date();
        boolean ref = (timeRecord.getWorkConfig().isShowFullTips() || timeRecord.getWorkConfig().isSimpleTips()) &&
                fatigue >= timeRecord.getWorkConfig().getWorkTime()
                && (null == timeRecord.getNextRestTime() ? true : DateUtil.compare(time, timeRecord.getNextRestTime()) >= 0);
        if (ref) {
            showTip();
        }
    }

    private static void showTip() {
        CompletableFuture.runAsync(() -> {
            //todo: 锁定键盘鼠标
            if (!stopRun()) {
                try {
                    Integer restTime = timeRecord.getWorkConfig().getRestTime();
                    TimeUnit timeUnit = timeRecord.getWorkConfig().getRestTimeUnit().getTimeUnit();
                    Console.log("休息执行等待");
                    boolean isSimpleTips = timeRecord.getWorkConfig().isSimpleTips();
                    Platform.runLater(() -> RestLockWindows.doRest(timeRecord.getWorkConfig().getTips(), restTime, timeUnit, isSimpleTips));
                    latch.await(restTime, timeUnit);
                    Console.log("休息等待结束");
                    if (timeRecord.getNextRestTime() == null) {
                        // 非强制关闭的情况下才重置
                        timeRecord.reSetFatigue();
                    }
                    if (!isSimpleTips) {
                        Platform.runLater(() -> RestLockWindows.stage.close());
                    }
                    setRunStatus(true);
                    //reSet latch
                    latch = new CountDownLatch(1);
                } catch (Exception e) {
                    Console.log(e);
                }
            }
        });
    }

    public static boolean isRunning() {
        return isRun;
    }

    public static boolean stopRun() {
        return isRun = false;
    }

    public static void setRunStatus(boolean ref) {
        isRun = ref;
    }

    private static boolean canRun() {
        return isRun && timeRecord.getOperationId().get() != 0;
    }


}
